﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Lm.Common.ExtensionMethods
{
    public static class StreamExt
    {
        /// <summary>
        /// 从流的当前位置开始，把之后的所有数据写到另外一个流
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns>一共传输了多少字节</returns>
        public static long WriteTo(this Stream from, Stream to)
        {
            var totalCount = 0;
            while (true)
            {
                var buf = new byte[1024];
                int count = from.Read(buf, 0, 1024);
                totalCount += count;
                if (count == 0)
                { break; }
                to.Write(buf, 0, count);
            }
            to.Flush();
            return totalCount;
        }

        /// <summary>
        /// 从流中读取指定数量的字节，如果流已到尾部，
        /// 但是读取的数量还达不到指定的数量，则返回实际读取到的数据，
        /// 此时指定的数量与返回的数量不相等。
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static byte[] Read(this Stream stream, int count)
        {
            byte[] buf = new byte[count];
            var readed = 0;
            while (true)
            {
                var i = stream.Read(buf, readed, count - readed);
                if (i == 0)
                { break; }
                readed += i;
                if (readed == count)
                { break; }
            }
            return buf.Take(readed).ToArray();
        }

        public static byte[] ReadToEnd(this Stream stream)
        {
            using (var ms = new System.IO.MemoryStream())
            {
                stream.WriteTo(ms);
                return ms.ToArray();
            }
        }
    }
}
